<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="theme-color" content="#0078E7"><meta name="author" content="爱肖彤真是太好了"><meta name="copyright" content="爱肖彤真是太好了"><meta name="generator" content="Hexo 5.1.1"><meta name="theme" content="hexo-theme-yun"><title>流畅的python学习记录 | 工藤旧二の博客</title><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@900&amp;display=swap" media="none" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/star-markdown-css@0.1.19/dist/yun/yun-markdown.min.css"><script src="//at.alicdn.com/t/font_1140697_stqaphw3j4.js" async></script><script src="https://cdn.jsdelivr.net/npm/scrollreveal/dist/scrollreveal.min.js" defer></script><script>document.addEventListener("DOMContentLoaded", () => {
  [".post-card",".post-content img"].forEach((target)=> {
    ScrollReveal().reveal(target);
  })
});
</script><link rel="shortcut icon" type="image/svg+xml" href="/task/yun.ico"><link rel="mask-icon" href="/task/yun.ico" color="#0078E7"><link rel="alternate icon" href="/yun.ico"><link rel="preload" href="/task/css/hexo-theme-yun.css" as="style"><link rel="preload" href="/task/js/utils.js" as="script"><link rel="preload" href="/task/js/hexo-theme-yun.js" as="script"><link rel="prefetch" href="/task/js/sidebar.js" as="script"><link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin><link rel="stylesheet" href="/task/css/hexo-theme-yun.css"><link rel="alternate" href="/task/atom.xml" title="工藤旧二の博客" type="application/atom+xml"><script id="yun-config">
    const Yun = window.Yun || {};
    window.CONFIG = {"root":"/task/","title":"工藤旧二の博客","version":"0.9.7","anonymous_image":"https://cdn.jsdelivr.net/gh/YunYouJun/cdn/img/avatar/none.jpg","say":{"api":"https://v1.hitokoto.cn","hitokoto":true},"local_search":{"path":"/task/search.xml"},"fireworks":{"colors":["102, 167, 221","62, 131, 225","33, 78, 194"]}};
  </script><script>(function(){
  var bp = document.createElement('script');
  var curProtocol = window.location.protocol.split(':')[0];
  if (curProtocol === 'https') {
    bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
  }
  else {
    bp.src = 'http://push.zhanzhang.baidu.com/push.js';
  }
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(bp, s);
})();</script><meta name="description" content="流畅的python学习记录第一章：python数据模型1 一副python风格的纸牌# import collections # Card &#x3D; collections.namedtuple(&#39;Card&#39;,[&#39;rank&#39;,&#39;suit&#39;]) # collections.namedtuple常用于创建一个只有少数属性但没有方法的类，比如数据库条目？  import collections  Card &#x3D;">
<meta property="og:type" content="article">
<meta property="og:title" content="流畅的python学习记录">
<meta property="og:url" content="http://huang_zhao.gitee.io/task/2021/06/27/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/%E6%B5%81%E7%95%85%E7%9A%84python%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/index.html">
<meta property="og:site_name" content="工藤旧二の博客">
<meta property="og:description" content="流畅的python学习记录第一章：python数据模型1 一副python风格的纸牌# import collections # Card &#x3D; collections.namedtuple(&#39;Card&#39;,[&#39;rank&#39;,&#39;suit&#39;]) # collections.namedtuple常用于创建一个只有少数属性但没有方法的类，比如数据库条目？  import collections  Card &#x3D;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gtcrmf3n0hj615s0nkac902.jpg">
<meta property="article:published_time" content="2021-06-27T06:10:11.000Z">
<meta property="article:modified_time" content="2021-08-11T09:18:42.000Z">
<meta property="article:author" content="爱肖彤真是太好了">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/008i3skNly1gtcrmf3n0hj615s0nkac902.jpg"><script src="/task/js/ui/mode.js"></script><link rel="stylesheet" href="/task/css/prism.css" type="text/css"></head><body><script defer src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script defer src="/task/js/ui/fireworks.js"></script><canvas class="fireworks"></canvas><div class="container"><a class="sidebar-toggle hty-icon-button" id="menu-btn"><div class="hamburger hamburger--spin" type="button"><span class="hamburger-box"><span class="hamburger-inner"></span></span></div></a><div class="sidebar-toggle sidebar-overlay"></div><aside class="sidebar"><script src="/task/js/sidebar.js"></script><ul class="sidebar-nav"><li class="sidebar-nav-item sidebar-nav-toc hty-icon-button sidebar-nav-active" data-target="post-toc-wrap" title="文章目录"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-list-ordered"></use></svg></li><li class="sidebar-nav-item sidebar-nav-overview hty-icon-button" data-target="site-overview-wrap" title="站点概览"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-passport-line"></use></svg></li></ul><div class="sidebar-panel" id="site-overview-wrap"><div class="site-info fix-top"><a class="site-author-avatar" href="/task/about/" title="爱肖彤真是太好了"><img width="96" loading="lazy" src="/task/Yun.png" alt="爱肖彤真是太好了"></a><div class="site-author-name"><a href="/task/about/">爱肖彤真是太好了</a></div><a class="site-name" href="/task/about/site.html">工藤旧二の博客</a><sub class="site-subtitle"></sub><div class="site-desciption"></div></div><nav class="site-state"><a class="site-state-item hty-icon-button icon-home" href="/task/" title="首页"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-home-4-line"></use></svg></span></a><div class="site-state-item"><a href="/task/archives/" title="归档"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-archive-line"></use></svg></span><span class="site-state-item-count">57</span></a></div><div class="site-state-item"><a href="/task/categories/" title="分类"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-2-line"></use></svg></span><span class="site-state-item-count">2</span></a></div><div class="site-state-item"><a href="/task/tags/" title="标签"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="site-state-item-count">50</span></a></div><a class="site-state-item hty-icon-button" target="_blank" rel="noopener" href="https://yun.yunyoujun.cn" title="文档"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-settings-line"></use></svg></span></a></nav><hr style="margin-bottom:0.5rem"><div class="links-of-author"><a class="links-of-author-item hty-icon-button" rel="noopener" title="RSS" target="_blank" style="color:orange"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-rss-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="QQ" target="_blank" style="color:#12B7F5"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-qq-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="GitHub" target="_blank" style="color:#6e5494"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-github-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="微博" target="_blank" style="color:#E6162D"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-weibo-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="豆瓣" target="_blank" style="color:#007722"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-douban-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://music.163.com/#/user/home?id=552858287" title="网易云音乐" target="_blank" style="color:#C20C0C"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-netease-cloud-music-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="知乎" target="_blank" style="color:#0084FF"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-zhihu-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://space.bilibili.com/15081363" title="哔哩哔哩" target="_blank" style="color:#FF8EB3"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-bilibili-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="Twitter" target="_blank" style="color:#1da1f2"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-twitter-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="Telegram Channel" target="_blank" style="color:#0088CC"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-telegram-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="E-Mail" target="_blank" style="color:#8E71C1"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-mail-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="Travelling" target="_blank" style="color:var(--hty-text-color)"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-send-plane-2-line"></use></svg></a></div><hr style="margin:0.5rem 1rem"><div class="links"><a class="links-item hty-icon-button" href="/task/links/" title="我的小伙伴们" style="color:dodgerblue"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-genderless-line"></use></svg></a></div><br><a class="links-item hty-icon-button" id="toggle-mode-btn" href="javascript:;" title="Mode" style="color: #f1cb64"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-contrast-2-line"></use></svg></a></div><div class="sidebar-panel sidebar-panel-active" id="post-toc-wrap"><div class="post-toc"><div class="post-toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B5%81%E7%95%85%E7%9A%84python%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95"><span class="toc-text">流畅的python学习记录</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%B8%80%E7%AB%A0%EF%BC%9Apython%E6%95%B0%E6%8D%AE%E6%A8%A1%E5%9E%8B"><span class="toc-text">第一章：python数据模型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E4%B8%80%E5%89%AFpython%E9%A3%8E%E6%A0%BC%E7%9A%84%E7%BA%B8%E7%89%8C"><span class="toc-text">1 一副python风格的纸牌</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E7%89%B9%E6%AE%8A%E6%96%B9%E6%B3%95"><span class="toc-text">2 如何使用特殊方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%BA%8C%E7%AB%A0%EF%BC%9A%E5%BA%8F%E5%88%97%E6%9E%84%E6%88%90%E7%9A%84%E6%95%B0%E7%BB%84"><span class="toc-text">第二章：序列构成的数组</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%8F%98%E9%87%8F%E6%B3%84%E9%9C%B2"><span class="toc-text">1 变量泄露</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E7%AC%9B%E5%8D%A1%E5%B0%94%E7%A7%AF%EF%BC%88%E5%A4%9A%E7%BB%B4%E5%88%97%E8%A1%A8%E7%94%9F%E6%88%90%E5%BC%8F%EF%BC%89"><span class="toc-text">2 笛卡尔积（多维列表生成式）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%85%B7%E5%90%8D%E5%85%83%E7%BB%84"><span class="toc-text">3 具名元组</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%83%E7%BB%84%E6%8B%86%E5%8C%85"><span class="toc-text">元组拆包</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E5%88%87%E7%89%87%E8%B5%8B%E5%80%BC"><span class="toc-text">4 切片赋值</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AF%B9%E5%BA%8F%E5%88%97%E4%BD%BF%E7%94%A8-%E5%92%8C"><span class="toc-text">*对序列使用+和**</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E7%94%B1%E5%88%97%E8%A1%A8%E7%BB%84%E6%88%90%E7%9A%84%E5%88%97%E8%A1%A8%EF%BC%88%E7%BB%86%E8%8A%82%EF%BC%89"><span class="toc-text">5 由列表组成的列表（细节）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E5%BA%8F%E5%88%97%E7%9A%84%E5%A2%9E%E9%87%8F%E8%B5%8B%E5%80%BC"><span class="toc-text">6 序列的增量赋值</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%B3%E4%BA%8E%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="toc-text">关于返回值</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%B8%89%E7%AB%A0%EF%BC%9A%E5%AD%97%E5%85%B8%E5%92%8C%E9%9B%86%E5%90%88"><span class="toc-text">第三章：字典和集合</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E6%98%A0%E5%B0%84%E7%9A%84%E5%BC%B9%E6%80%A7%E9%94%AE%E6%9F%A5%E8%AF%A2"><span class="toc-text">1 映射的弹性键查询</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-1-defaultdict%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">1.1 defaultdict的使用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-missing-%E4%BD%BF%E7%94%A8"><span class="toc-text">1.2 __missing__使用</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%AD%97%E5%85%B8%E7%9A%84%E5%8F%98%E7%A7%8D"><span class="toc-text">2 字典的变种</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E4%B8%8D%E5%8F%AF%E5%8F%98%E7%9A%84%E6%98%A0%E5%B0%84%E7%B1%BB%E5%9E%8B"><span class="toc-text">3 不可变的映射类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E9%9B%86%E5%90%88"><span class="toc-text">4 集合</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E5%AD%97%E5%85%B8%E4%B8%AD%E7%9A%84%E6%95%A3%E5%88%97%E8%A1%A8"><span class="toc-text">5 字典中的散列表</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%95%A3%E5%88%97%E8%A1%A8%EF%BC%88%E5%93%88%E5%B8%8C%E8%A1%A8%EF%BC%89%E6%89%A9%E5%B1%95"><span class="toc-text">散列表（哈希表）扩展</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E5%A4%84%E7%90%86hash%E5%86%B2%E7%AA%81"><span class="toc-text">如何处理hash冲突</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#dict%E7%9A%84%E5%BA%95%E5%B1%82%E5%AE%9E%E7%8E%B0"><span class="toc-text">dict的底层实现</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E5%9B%9B%E7%AB%A0-%E5%AD%97%E8%8A%82%E4%B8%8E%E5%BA%8F%E5%88%97"><span class="toc-text">第四章 字节与序列</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%BA%94%E7%AB%A0-%E4%B8%80%E7%AD%89%E5%87%BD%E6%95%B0"><span class="toc-text">第五章 一等函数</span></a></li></ol></li></ol></div></div></div></aside><main class="sidebar-translate" id="content"><div id="post"><article class="post-block" itemscope itemtype="https://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://huang_zhao.gitee.io/task/task/2021/06/27/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/%E6%B5%81%E7%95%85%E7%9A%84python%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/"><span hidden itemprop="author" itemscope itemtype="https://schema.org/Person"><meta itemprop="name" content="爱肖彤真是太好了"><meta itemprop="description"></span><span hidden itemprop="publisher" itemscope itemtype="https://schema.org/Organization"><meta itemprop="name" content="工藤旧二の博客"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">流畅的python学习记录</h1><div class="post-meta"><div class="post-time" style="display:block"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-calendar-line"></use></svg></span> <time title="创建时间：2021-06-27 14:10:11" itemprop="dateCreated datePublished" datetime="2021-06-27T14:10:11+08:00">2021-06-27</time><span class="post-meta-divider">-</span><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-calendar-2-line"></use></svg></span> <time title="修改时间：2021-08-11 17:18:42" itemprop="dateModified" datetime="2021-08-11T17:18:42+08:00">2021-08-11</time></div><span class="post-count"><span class="post-symbolcount"><span class="post-meta-item-icon" title="本文字数"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-file-word-line"></use></svg></span> <span title="本文字数">4.2k</span><span class="post-meta-divider">-</span><span class="post-meta-item-icon" title="阅读时长"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-timer-line"></use></svg></span> <span title="阅读时长">16m</span></span></span><span class="post-busuanzi"><span class="post-meta-divider">-</span><span class="post-meta-item-icon" title="阅读次数"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-eye-line"></use></svg> <span id="busuanzi_value_page_pv"></span></span></span><div class="post-classify"><span class="post-category"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-line"></use></svg></span> <span itemprop="about" itemscope itemtype="https://schema.org/Thing"><a class="category" href="/task/categories/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/" style="--text-color:var(--hty-text-color)" itemprop="url" rel="index"><span itemprop="text">读书笔记</span></a></span></span><span class="post-tag"><span class="post-meta-divider">-</span><a class="tag" href="/task/tags/python/" style="--text-color:var(--hty-text-color)"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">python</span></a></span></div></div></header><section class="post-body" itemprop="articleBody"><div class="post-content markdown-body" style="--smc-primary:#0078E7;"><h1 id="流畅的python学习记录"><a href="#流畅的python学习记录" class="headerlink" title="流畅的python学习记录"></a>流畅的python学习记录</h1><h2 id="第一章：python数据模型"><a href="#第一章：python数据模型" class="headerlink" title="第一章：python数据模型"></a>第一章：python数据模型</h2><h3 id="1-一副python风格的纸牌"><a href="#1-一副python风格的纸牌" class="headerlink" title="1 一副python风格的纸牌"></a>1 一副python风格的纸牌</h3><pre class=" language-python"><code class="language-python"><span class="token comment" spellcheck="true"># import collections</span>
<span class="token comment" spellcheck="true"># Card = collections.namedtuple('Card',['rank','suit'])</span>
<span class="token comment" spellcheck="true"># collections.namedtuple常用于创建一个只有少数属性但没有方法的类，比如数据库条目？</span>

<span class="token keyword">import</span> collections

Card <span class="token operator">=</span> collections<span class="token punctuation">.</span>namedtuple<span class="token punctuation">(</span><span class="token string">'Card'</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string">'rank'</span><span class="token punctuation">,</span> <span class="token string">'suit'</span><span class="token punctuation">]</span><span class="token punctuation">)</span>


<span class="token keyword">class</span> <span class="token class-name">FrenchDeck</span><span class="token punctuation">:</span>
    ranks <span class="token operator">=</span> <span class="token punctuation">[</span>str<span class="token punctuation">(</span>n<span class="token punctuation">)</span> <span class="token keyword">for</span> n <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">11</span><span class="token punctuation">)</span><span class="token punctuation">]</span> <span class="token operator">+</span> list<span class="token punctuation">(</span><span class="token string">'JQKA'</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># 用于创建一组牌</span>
    suits <span class="token operator">=</span> <span class="token string">'spades diamonds clubs hearts'</span><span class="token punctuation">.</span>split<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># 用于创建一个组</span>

    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>_cards <span class="token operator">=</span> <span class="token punctuation">[</span>Card<span class="token punctuation">(</span>rank<span class="token punctuation">,</span> suit<span class="token punctuation">)</span>
                       <span class="token keyword">for</span> suit <span class="token keyword">in</span> self<span class="token punctuation">.</span>suits
                            <span class="token keyword">for</span> rank <span class="token keyword">in</span> self<span class="token punctuation">.</span>ranks<span class="token punctuation">]</span>
                        <span class="token comment" spellcheck="true"># 列表生成式，每循环一次生成一个对象</span>

    <span class="token keyword">def</span> <span class="token function">__len__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> len<span class="token punctuation">(</span>self<span class="token punctuation">.</span>_cards<span class="token punctuation">)</span>
    <span class="token keyword">def</span> <span class="token function">__getitem__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> position<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> self<span class="token punctuation">.</span>_cards<span class="token punctuation">[</span>position<span class="token punctuation">]</span>
deck <span class="token operator">=</span> FrenchDeck<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># print(deck.ranks)</span>
<span class="token comment" spellcheck="true"># print(deck.suits)</span>
<span class="token comment" spellcheck="true"># print(deck._cards[51])</span>
<span class="token comment" spellcheck="true"># print(len(deck))</span>

<span class="token keyword">import</span> random
<span class="token comment" spellcheck="true"># 24点小游戏</span>
game24 <span class="token operator">=</span> random<span class="token punctuation">.</span>sample<span class="token punctuation">(</span>deck<span class="token punctuation">.</span>_cards<span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># print(game24)</span>
res <span class="token operator">=</span> <span class="token punctuation">[</span>i<span class="token punctuation">.</span>rank <span class="token keyword">for</span> i <span class="token keyword">in</span> game24<span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># res = map(lambda card:card.rank,game24)</span>
<span class="token comment" spellcheck="true"># print(res)</span>

</code></pre>
<p>总结：</p>
<p>1 学会了一个快速实例化得到对象的方法<code>collections.namedtuple</code>由这个方法得到的对象只有属性没有方法</p>
<p>2 我们在创建一个数据模型的时候，尽量把它做得像基本数据类型，比如说我要看这个牌对象的总张数，不需要去想是obj.length还是obj.len()。应当做成<code>res = len(obj)</code>一样简洁明了</p>
<h3 id="2-如何使用特殊方法"><a href="#2-如何使用特殊方法" class="headerlink" title="2 如何使用特殊方法"></a>2 如何使用特殊方法</h3><p>python中的特殊方法比如<code>__len__</code>并不是拿来给我们直接使用的，而是给解释器使用的，也就是说没有<code>obj.__len__()</code>这种写法。这里要注意一个小点：<code>len(obj)</code>如果这个obj是一个自定义类的对象，那会调用这个对象的<code>__len__</code>方法，如果obj是python的一个基本数据类型，那CPython会抄个近路，<code>__len__</code>实际上会直接返回 PyVarObject 里的 ob_size 属 性，PyVarObject 是表示内存中长度可变的内置对象的 C 语言结构体。直接读取这个值比 调用一个方法要快很多。</p>
<p><strong>python实现向量</strong></p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">from</span> math <span class="token keyword">import</span> hypot


<span class="token keyword">class</span> <span class="token class-name">Vector</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> x<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>x <span class="token operator">=</span> x
        self<span class="token punctuation">.</span>y <span class="token operator">=</span> y

    <span class="token keyword">def</span> <span class="token function">__repr__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> <span class="token string">'Vector(%r, %r)'</span> <span class="token operator">%</span> <span class="token punctuation">(</span>self<span class="token punctuation">.</span>x<span class="token punctuation">,</span> self<span class="token punctuation">.</span>y<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__abs__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> hypot<span class="token punctuation">(</span>self<span class="token punctuation">.</span>x<span class="token punctuation">,</span> self<span class="token punctuation">.</span>y<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__bool__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> bool<span class="token punctuation">(</span>abs<span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__add__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> other<span class="token punctuation">)</span><span class="token punctuation">:</span>
        x <span class="token operator">=</span> self<span class="token punctuation">.</span>x <span class="token operator">+</span> other<span class="token punctuation">.</span>x
        y <span class="token operator">=</span> self<span class="token punctuation">.</span>y <span class="token operator">+</span> other<span class="token punctuation">.</span>y
        <span class="token keyword">return</span> Vector<span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__mul__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> scalar<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> Vector<span class="token punctuation">(</span>self<span class="token punctuation">.</span>x <span class="token operator">*</span> scalar<span class="token punctuation">,</span> self<span class="token punctuation">.</span>y <span class="token operator">*</span> scalar<span class="token punctuation">)</span>


<span class="token comment" spellcheck="true"># v1 = Vector(1,2)</span>
<span class="token comment" spellcheck="true"># v2 = Vector(3,4)</span>

<span class="token comment" spellcheck="true"># print(v)</span>
</code></pre>
<p><strong>测试<code>__bool__,__len__</code></strong></p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Mynum</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>num<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>num <span class="token operator">=</span> num
        self<span class="token punctuation">.</span>l1 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
    <span class="token comment" spellcheck="true"># def __bool__(self):</span>
    <span class="token comment" spellcheck="true">#     if self.num&lt;10:</span>
    <span class="token comment" spellcheck="true">#         return False</span>
    <span class="token comment" spellcheck="true">#     return True</span>
    <span class="token keyword">def</span> <span class="token function">__len__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> self<span class="token punctuation">.</span>l1<span class="token punctuation">:</span>
            <span class="token comment" spellcheck="true"># 如果l1有值则返回真</span>
            <span class="token keyword">return</span> <span class="token boolean">True</span>
        <span class="token keyword">return</span> <span class="token boolean">False</span>

num <span class="token operator">=</span> Mynum<span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># num.l1.append(123)</span>
<span class="token comment" spellcheck="true"># 在这里调用了对象的__bool__方法</span>
<span class="token keyword">if</span> num<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token number">123</span><span class="token punctuation">)</span></code></pre>
<p>总结：</p>
<p>1 <code>__repr__</code> 和 <code>__str__</code> 的区别在于，后者是在 str() 函数被使用，或是在用 print 函数打印 一个对象的时候才被调用的，并且它返回的字符串对终端用户更友好。 如果你只想实现这两个特殊方法中的一个，<code>__repr__</code> 是更好的选择，因为如果一个对象没 有 <code>__str__</code> 函数，而 Python 又需要调用它的时候，解释器会用 <code>__repr__</code> 作为替代。</p>
<p>2 中缀运算符的基本原则就是不改变操作对 象，而是产出一个新的值,就像如果我们要构造一个x+y，那得到的结果就不应该影响xy原本的数值，而应该返回一个新值</p>
<p>3 python中在判断一个值是真还是假就会调用<code>bool(x)</code>这个函数只会返回True/False，如果这个对象没有<code>__bool__</code>方法，那python就会尝试使用它的<code>__len__</code>如果长度是0，返回False</p>
<p><strong>表1-1：跟运算符无关的特殊方法</strong></p>
<table>
<thead>
<tr>
<th>类别</th>
<th>方法名</th>
</tr>
</thead>
<tbody><tr>
<td>字符串 / 字节序列 表示形式</td>
<td><code>__repr__、__str__、__format__、__bytes__</code></td>
</tr>
<tr>
<td>数值转换</td>
<td><code>__abs__、__bool__、__complex__、__int__、__float__、__hash__、__index__</code></td>
</tr>
<tr>
<td>集合模拟</td>
<td><code>__len__、__getitem__、__setitem__、__delitem__、__contains__</code></td>
</tr>
<tr>
<td>迭代枚举</td>
<td><code>__iter__、__reversed__、__next__</code></td>
</tr>
<tr>
<td>可调用模拟</td>
<td><code>__call__</code></td>
</tr>
<tr>
<td>上下文管理</td>
<td><code>__enter__、__exit__</code></td>
</tr>
<tr>
<td>实例创建和销毁</td>
<td><code>__new__、__init__、__del__</code></td>
</tr>
<tr>
<td>属性管理</td>
<td><code>__getattr__、__getattribute__、__setattr__、__delattr__、__dir__</code></td>
</tr>
<tr>
<td>属性描述符</td>
<td><code>__get__、__set__、__delete__</code></td>
</tr>
<tr>
<td>跟类相关的服务</td>
<td><code>__prepare__、__instancecheck__、__subclasscheck__</code></td>
</tr>
</tbody></table>
<p><strong>表1-2：跟运算符相关的特殊方法</strong></p>
<table>
<thead>
<tr>
<th>类别</th>
<th>方法名和对应的运算符</th>
</tr>
</thead>
<tbody><tr>
<td>一元运算符</td>
<td><code>__neg__ -、__pos__ +、__abs__ abs()</code></td>
</tr>
<tr>
<td>众多比较运算符</td>
<td><code>__lt__ &lt;、__le__ &lt;=、__eq__ ==、__ne__ !=、__gt__ &gt;、__ge__ &gt;=</code></td>
</tr>
<tr>
<td>算术运算符</td>
<td><code>__add__ +、__sub__ -、__mul__ *、__truediv__ /、__floordiv__ //、__ mod__ %、__divmod__ divmod()、__pow__ ** 或 pow()、__round__ round()</code></td>
</tr>
<tr>
<td>反向算术运算符</td>
<td><code>__radd__、__rsub__、__rmul__、__rtruediv__、__rfloordiv__、__rmod__、 __rdivmod__、__rpow__</code></td>
</tr>
<tr>
<td>增量赋值算术运算符</td>
<td><code>__iadd__、__isub__、__imul__、__itruediv__、__ifloordiv__、__imod__、 __ipow__</code></td>
</tr>
<tr>
<td>位运算符</td>
<td><code>__invert__ ~、__lshift__ &lt;&lt;、__rshift__ &gt;&gt;、__and__ &amp;、__or__</code></td>
</tr>
<tr>
<td>反向位运算符</td>
<td><code>__rlshift__、__rrshift__、__rand__、__rxor__、__ror__</code></td>
</tr>
<tr>
<td>增量赋值位运算符</td>
<td><code>__ilshift__、__irshift__、__iand__、__ixor__、__ior__</code></td>
</tr>
</tbody></table>
<h2 id="第二章：序列构成的数组"><a href="#第二章：序列构成的数组" class="headerlink" title="第二章：序列构成的数组"></a>第二章：序列构成的数组</h2><h3 id="1-变量泄露"><a href="#1-变量泄露" class="headerlink" title="1 变量泄露"></a>1 变量泄露</h3><p>python2中使用列表生成式容易造成变量泄露的问题，例如：</p>
<pre class=" language-python"><code class="language-python"><span class="token comment" spellcheck="true"># python2.7中</span>
x <span class="token operator">=</span> <span class="token string">'my precious'</span>
dummy <span class="token operator">=</span> <span class="token punctuation">[</span>x <span class="token keyword">for</span> x <span class="token keyword">in</span> <span class="token string">'ABC'</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'C'</span>

<span class="token comment" spellcheck="true"># python3.x中</span>
x <span class="token operator">=</span> <span class="token string">'ABC'</span>
dummy <span class="token operator">=</span> <span class="token punctuation">[</span>ord<span class="token punctuation">(</span>x<span class="token punctuation">)</span> <span class="token keyword">for</span> x <span class="token keyword">in</span> x<span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span> 
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'ABC'</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>dummy<span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token number">65</span><span class="token punctuation">,</span> <span class="token number">66</span><span class="token punctuation">,</span> <span class="token number">67</span><span class="token punctuation">]</span> </code></pre>
<h3 id="2-笛卡尔积（多维列表生成式）"><a href="#2-笛卡尔积（多维列表生成式）" class="headerlink" title="2 笛卡尔积（多维列表生成式）"></a>2 笛卡尔积（多维列表生成式）</h3><pre class=" language-python"><code class="language-python">colors <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'black'</span><span class="token punctuation">,</span> <span class="token string">'white'</span><span class="token punctuation">]</span>
sizes <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'S'</span><span class="token punctuation">,</span> <span class="token string">'M'</span><span class="token punctuation">,</span> <span class="token string">'L'</span><span class="token punctuation">]</span>
tshirts <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">(</span>color<span class="token punctuation">,</span> size<span class="token punctuation">)</span> <span class="token keyword">for</span> size <span class="token keyword">in</span> sizes
           <span class="token keyword">for</span> color <span class="token keyword">in</span> colors<span class="token punctuation">]</span></code></pre>
<h3 id="3-具名元组"><a href="#3-具名元组" class="headerlink" title="3 具名元组"></a>3 具名元组</h3><p>collections.namedtuple 是一个工厂函数，它可以用来构建一个带字段名的元组和一个有 名字的类——这个带名字的类对调试程序有很大帮助。</p>
<p>创建一个具名元组需要两个参数，一个是类名，另一个是类的各个字段的名字。后者可 以是由数个字符串组成的可迭代对象，或者是由空格分隔开的字段名组成的字符串。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">from</span> collections <span class="token keyword">import</span> namedtuple
City <span class="token operator">=</span> namedtuple<span class="token punctuation">(</span><span class="token string">'City'</span><span class="token punctuation">,</span> <span class="token string">'name country population coordinates'</span><span class="token punctuation">)</span> </code></pre>
<h4 id="元组拆包"><a href="#元组拆包" class="headerlink" title="元组拆包"></a>元组拆包</h4><pre class=" language-python"><code class="language-python">a<span class="token punctuation">,</span> b<span class="token punctuation">,</span> <span class="token operator">*</span>rest <span class="token operator">=</span> range<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># a, b, rest (0, 1, [2, 3, 4])</span>
a<span class="token punctuation">,</span> b<span class="token punctuation">,</span> <span class="token operator">*</span>rest <span class="token operator">=</span> range<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># a, b, rest (0, 1, [2])</span>
a<span class="token punctuation">,</span> b<span class="token punctuation">,</span> <span class="token operator">*</span>rest <span class="token operator">=</span> range<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># a, b, rest (0, 1, [])</span></code></pre>
<h3 id="4-切片赋值"><a href="#4-切片赋值" class="headerlink" title="4 切片赋值"></a>4 <strong>切片赋值</strong></h3><pre class=" language-python"><code class="language-python">l <span class="token operator">=</span> list<span class="token punctuation">(</span>range<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span> 
l<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">:</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">30</span><span class="token punctuation">]</span> 
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">30</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">9</span><span class="token punctuation">]</span> 
l<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">:</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">100</span> <span class="token comment" spellcheck="true"># 如果赋值对象是一个切片，那赋值语句的右侧必须是一个可迭代对象</span>
l<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">:</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">100</span><span class="token punctuation">]</span> <span class="token comment" spellcheck="true"># 可以执行</span></code></pre>
<h4 id="对序列使用-和"><a href="#对序列使用-和" class="headerlink" title="*对序列使用+和**"></a>*<em>对序列使用+和**</em></h4><p>对序列使用*与+的时候，要知道，得到的是一个新的结果不会再原来的结果上修改</p>
<p>但是如果a*n中，序列a中包含了其他可变类型的话，内部可变类型的复制，最终指向的都是同一个内存地址</p>
<pre class=" language-python"><code class="language-python">my_list <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">]</span> <span class="token operator">*</span> <span class="token number">3</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>my_list<span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
my_list<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>my_list<span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span></code></pre>
<h3 id="5-由列表组成的列表（细节）"><a href="#5-由列表组成的列表（细节）" class="headerlink" title="5 由列表组成的列表（细节）"></a>5 由列表组成的列表（细节）</h3><p>正确方式</p>
<pre class=" language-python"><code class="language-python"> board <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">]</span> <span class="token operator">*</span> <span class="token number">3</span> <span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">]</span>
 <span class="token operator">>></span><span class="token operator">></span> board <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">]</span><span class="token punctuation">]</span> 

 board<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">'X'</span>
 <span class="token operator">>></span><span class="token operator">></span>board <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'X'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">]</span><span class="token punctuation">]</span></code></pre>
<p>错误方式</p>
<pre class=" language-python"><code class="language-python">weird_board <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">]</span> <span class="token operator">*</span> <span class="token number">3</span><span class="token punctuation">]</span> <span class="token operator">*</span> <span class="token number">3</span> 
<span class="token operator">>></span><span class="token operator">></span> weird_board <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">]</span><span class="token punctuation">]</span> 

weird_board<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">'O'</span> 
<span class="token operator">>></span><span class="token operator">></span> weird_board <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'O'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'O'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'_'</span><span class="token punctuation">,</span> <span class="token string">'O'</span><span class="token punctuation">]</span><span class="token punctuation">]</span></code></pre>
<h3 id="6-序列的增量赋值"><a href="#6-序列的增量赋值" class="headerlink" title="6 序列的增量赋值"></a>6 序列的增量赋值</h3><p>序列的增量赋值主要对比是以下两种写法</p>
<ul>
<li><pre class=" language-python"><code class="language-python">a <span class="token operator">=</span> a <span class="token operator">+</span> b  <span class="token comment" spellcheck="true"># 创建了新的a</span></code></pre>
</li>
<li><pre class=" language-python"><code class="language-python">a<span class="token operator">+=</span>b <span class="token comment" spellcheck="true"># 在a的基础上修改</span></code></pre>
</li>
</ul>
<p>+= 背后的特殊方法是 <em>iadd__ （用于“就地加法”）。但是如果一个类没有实现这个方法的话，Python 会退一步调用 <em>add</em></em> </p>
<p>对不可变类型进行+=操作的效率非常低，因为每次都会产生一个新的对象</p>
<p><strong>但是str不同</strong>，因为str的+=操作太频繁了，cpython对此进行了优化，在初始化str的时候就先预留了后续扩展的空间，因此不会创建新的值</p>
<h4 id="关于返回值"><a href="#关于返回值" class="headerlink" title="关于返回值"></a><strong>关于返回值</strong></h4><p>要判断一个语句的返回值是什么，首先判断的是是否会产生新值，这句话也可以逆向判断，例如<code>list.sort</code>的返回值是None，那我们就可以知道得到的列表还是原来的列表，并没有新值产生，当然只针对内置的数据类型的基本方法。</p>
<p>继续展开对例子的描述</p>
<p><code>列表的方法：list.sort 与内置函数sorted()对比</code></p>
<p><strong>最大的区别就是</strong>，<code>list.sort</code>是在原列表上直接排序，返回值None，内置函数<code>sorted</code>是创建一个新列表，源列表不动，返回值为新排序列表</p>
<p>这两种方法都有两个可选参数：</p>
<ul>
<li>reverse<ul>
<li>默认False，降序，可改为True，升序</li>
</ul>
</li>
<li>key<ul>
<li>一个只有一个参数的函数，不写的话，就是按自己的值排序，比如<code>key=str.lower</code>来实现忽略大小写，注意这里不能加括号调用</li>
</ul>
</li>
</ul>
<pre class=" language-python"><code class="language-python">fruits <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'grape'</span><span class="token punctuation">,</span> <span class="token string">'raspberry'</span><span class="token punctuation">,</span> <span class="token string">'apple'</span><span class="token punctuation">,</span> <span class="token string">'banana'</span><span class="token punctuation">]</span>

sorted<span class="token punctuation">(</span>fruits<span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token string">'apple'</span><span class="token punctuation">,</span> <span class="token string">'banana'</span><span class="token punctuation">,</span> <span class="token string">'grape'</span><span class="token punctuation">,</span> <span class="token string">'raspberry'</span><span class="token punctuation">]</span> ➊

fruits
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token string">'grape'</span><span class="token punctuation">,</span> <span class="token string">'raspberry'</span><span class="token punctuation">,</span> <span class="token string">'apple'</span><span class="token punctuation">,</span> <span class="token string">'banana'</span><span class="token punctuation">]</span> ➋

sorted<span class="token punctuation">(</span>fruits<span class="token punctuation">,</span> reverse<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token string">'raspberry'</span><span class="token punctuation">,</span> <span class="token string">'grape'</span><span class="token punctuation">,</span> <span class="token string">'banana'</span><span class="token punctuation">,</span> <span class="token string">'apple'</span><span class="token punctuation">]</span> ➌

sorted<span class="token punctuation">(</span>fruits<span class="token punctuation">,</span> key<span class="token operator">=</span>len<span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token string">'grape'</span><span class="token punctuation">,</span> <span class="token string">'apple'</span><span class="token punctuation">,</span> <span class="token string">'banana'</span><span class="token punctuation">,</span> <span class="token string">'raspberry'</span><span class="token punctuation">]</span> ➍

sorted<span class="token punctuation">(</span>fruits<span class="token punctuation">,</span> key<span class="token operator">=</span>len<span class="token punctuation">,</span> reverse<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token string">'raspberry'</span><span class="token punctuation">,</span> <span class="token string">'banana'</span><span class="token punctuation">,</span> <span class="token string">'grape'</span><span class="token punctuation">,</span> <span class="token string">'apple'</span><span class="token punctuation">]</span> ➎

fruits
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token string">'grape'</span><span class="token punctuation">,</span> <span class="token string">'raspberry'</span><span class="token punctuation">,</span> <span class="token string">'apple'</span><span class="token punctuation">,</span> <span class="token string">'banana'</span><span class="token punctuation">]</span> ➏

fruits<span class="token punctuation">.</span>sort<span class="token punctuation">(</span><span class="token punctuation">)</span> ➐
fruits
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">[</span><span class="token string">'apple'</span><span class="token punctuation">,</span> <span class="token string">'banana'</span><span class="token punctuation">,</span> <span class="token string">'grape'</span><span class="token punctuation">,</span> <span class="token string">'raspberry'</span><span class="token punctuation">]</span> ➑</code></pre>
<h2 id="第三章：字典和集合"><a href="#第三章：字典和集合" class="headerlink" title="第三章：字典和集合"></a>第三章：字典和集合</h2><p>dict的key的要求是可散列对象，也就是可哈希，由于哈希碰撞的产生，所以可散列对象必须是不可变的，且如果是容器类型，容器类型内的元素也必须是可散列的</p>
<p>可散列：如果一个对象是可散列的，那么在这个对象的生命周期中，它 的散列值是不变的，而且这个对象需要实现<code> __hash__()</code> 方 法。另外可散列对象还要有<code> __qe__()</code> 方法，这样才能跟其他 键做比较。如果两个可散列对象是相等的，那么它们的散列值 一定是一样的…… </p>
<h3 id="1-映射的弹性键查询"><a href="#1-映射的弹性键查询" class="headerlink" title="1 映射的弹性键查询"></a>1 映射的弹性键查询</h3><p>如果有这么一个需求，在字典中查询一个值，如果查询不到，给我们返回一个特定的值。完成这个需求有两个方法，一是使用defaultdict这个类型而不是使用普通的dict，二是自己写一个新的dict继承dict然后重写<code>__missing__</code>方法</p>
<p>注意：defaultdict实现的原理就是重写了<code>__missing__</code>方法，所以也只会在[]取值找不到的时候调用</p>
<h4 id="1-1-defaultdict的使用"><a href="#1-1-defaultdict的使用" class="headerlink" title="1.1 defaultdict的使用"></a>1.1 defaultdict的使用</h4><pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> collections
<span class="token keyword">def</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string">'没有找到指定的值'</span>
<span class="token comment" spellcheck="true"># defaultdict如果索引找不到值会调用实例化的时候传入的第一个可调用对象</span>
<span class="token comment" spellcheck="true"># 将它的返回值作为a['xx']的返回值返回</span>
a <span class="token operator">=</span> collections<span class="token punctuation">.</span>defaultdict<span class="token punctuation">(</span><span class="token keyword">lambda</span> <span class="token punctuation">:</span><span class="token string">'没有找到指定的值'</span><span class="token punctuation">,</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># a = collections.defaultdict(test,{})</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>a<span class="token punctuation">[</span><span class="token string">'xx'</span><span class="token punctuation">]</span><span class="token punctuation">)</span></code></pre>
<h4 id="1-2-missing-使用"><a href="#1-2-missing-使用" class="headerlink" title="1.2 __missing__使用"></a>1.2 <code>__missing__</code>使用</h4><p>在映射类型找不到键的时候都会牵扯到<code>__missing__</code>，虽然dict没有写这个方法，但是它知道有这个东西的存在，也就是如果我们重写了这个方法，并继承dict，那在<code>__getitem__</code>进行取值的时候只要找不到，就会自动调用这个方法而不是返回报错信息。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">CommonDict</span><span class="token punctuation">(</span>dict<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__missing__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> f<span class="token string">'{key}这种键不存在于该字典中'</span>
dict1 <span class="token operator">=</span> CommonDict<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>dict1<span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>dict1<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token number">1</span>这种键不存在于该字典中</code></pre>
<h3 id="2-字典的变种"><a href="#2-字典的变种" class="headerlink" title="2 字典的变种"></a>2 字典的变种</h3><p>collections.OrderedDict </p>
<p>这个类型在添加键的时候会保持顺序，因此键的迭代次序总是一致 的。OrderedDict 的 popitem 方法默认删除并返回的是字典里的最后 一个元素，但是如果像 my_odict.popitem(last=False) 这样调用 它，那么它删除并返回第一个被添加进去的元素。 </p>
<p>collections.Counter</p>
<p>这个映射类型会给键准备一个整数计数器。每次更新一个键的时候都会增加这个计数器。所以这个类型可以用来给可散列表对象计数，或者是当成多重集来用——多重集合就是集合里的元素可以出现不止一次。Counter 实现了 + 和 - 运算符用来合并记录，还有像most_common([n]) 这类很有用的方法。most_common([n]) 会按照次序返回映射里最常见的 n 个键和它们的计数</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> collections

ct <span class="token operator">=</span> collections<span class="token punctuation">.</span>Counter<span class="token punctuation">(</span><span class="token string">'abracadabra'</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ct<span class="token punctuation">)</span>
ct<span class="token punctuation">.</span>update<span class="token punctuation">(</span><span class="token string">'aaaaazzz'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ct<span class="token punctuation">)</span></code></pre>
<p><strong>通过userDict扩展映射类型</strong></p>
<p>当我们要扩展dict的时候通常使用<strong>UserDict</strong> 作为基类，dict有时 会在某些方法的实现上走一些捷径，导致我们不得不在它的子类中重写这些方法，但是 UserDict 就不会带来这些问题。</p>
<p>tips：userDict不是dict的子类，只是在一个data的属性中使用了dict进行存储，这样设计解决了在点拦截和中括号拦截时的递归问题</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> collections


<span class="token keyword">class</span> <span class="token class-name">StrKeyDict</span><span class="token punctuation">(</span>collections<span class="token punctuation">.</span>UserDict<span class="token punctuation">)</span><span class="token punctuation">:</span> 

    <span class="token keyword">def</span> <span class="token function">__missing__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">:</span> 
        <span class="token keyword">if</span> isinstance<span class="token punctuation">(</span>key<span class="token punctuation">,</span> str<span class="token punctuation">)</span><span class="token punctuation">:</span> 
            <span class="token keyword">raise</span> KeyError<span class="token punctuation">(</span>key<span class="token punctuation">)</span>
        <span class="token keyword">return</span> self<span class="token punctuation">[</span>str<span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">]</span>


    <span class="token keyword">def</span> <span class="token function">__contains__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">:</span> 
        <span class="token keyword">return</span> str<span class="token punctuation">(</span>key<span class="token punctuation">)</span> <span class="token keyword">in</span> self<span class="token punctuation">.</span>data


    <span class="token keyword">def</span> <span class="token function">__setitem__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> key<span class="token punctuation">,</span> item<span class="token punctuation">)</span><span class="token punctuation">:</span> 
        self<span class="token punctuation">.</span>data<span class="token punctuation">[</span>str<span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">]</span> <span class="token operator">=</span> item

</code></pre>
<h3 id="3-不可变的映射类型"><a href="#3-不可变的映射类型" class="headerlink" title="3 不可变的映射类型"></a>3 不可变的映射类型</h3><p>标准库中所有的映射类型都是可变的，但是我们可能会有这样的需求，不能让用户错误的修改某个映射，在现实中实现这样的需求有一个很具体的例子：如果我们有一个密码锁，别人能看到密码锁，但是不能修改，我们自己也能看到但是能修改。这种情况只要在密码锁上放一层玻璃覆盖，外人是无法隔着玻璃修改原值的，而我们可以把玻璃拿掉去修改原值，且原值和玻璃后的值应当是同步更新的。</p>
<p>从 Python 3.3 开始，<strong>types</strong> 模块中引入了一个封装类名叫 <strong>MappingProxyType</strong>。如果给这个类 一个映射，它会返回一个只读的映射视图。虽然是个只读视图，但是它是动态的。这意味 着如果对原映射做出了改动，我们通过这个视图可以观察到，但是无法通过这个视图对原 映射做出修改。</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">from</span> types <span class="token keyword">import</span> MappingProxyType
d <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token string">'name'</span><span class="token punctuation">:</span><span class="token string">'hz'</span><span class="token punctuation">}</span>
d_map <span class="token operator">=</span> MappingProxyType<span class="token punctuation">(</span>d<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>d_map<span class="token punctuation">,</span>type<span class="token punctuation">(</span>d_map<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">{</span><span class="token string">'name'</span><span class="token punctuation">:</span> <span class="token string">'hz'</span><span class="token punctuation">}</span> <span class="token operator">&lt;</span><span class="token keyword">class</span> <span class="token string">'mappingproxy'</span><span class="token operator">></span>

d<span class="token punctuation">[</span><span class="token string">'age'</span><span class="token punctuation">]</span>  <span class="token operator">=</span><span class="token number">18</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>d_map<span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token punctuation">{</span><span class="token string">'name'</span><span class="token punctuation">:</span> <span class="token string">'hz'</span><span class="token punctuation">,</span> <span class="token string">'age'</span><span class="token punctuation">:</span> <span class="token number">18</span><span class="token punctuation">}</span></code></pre>
<h3 id="4-集合"><a href="#4-集合" class="headerlink" title="4 集合"></a>4 集合</h3><pre class=" language-python"><code class="language-python">needles <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">]</span>
haystack <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span>
found <span class="token operator">=</span> len<span class="token punctuation">(</span>set<span class="token punctuation">(</span>needles<span class="token punctuation">)</span> <span class="token operator">&amp;</span> set<span class="token punctuation">(</span>haystack<span class="token punctuation">)</span><span class="token punctuation">)</span>
found <span class="token operator">=</span> len<span class="token punctuation">(</span>set<span class="token punctuation">(</span>needles<span class="token punctuation">)</span><span class="token punctuation">.</span>intersection<span class="token punctuation">(</span>haystack<span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 两种写法都可以</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>found<span class="token punctuation">)</span></code></pre>
<h3 id="5-字典中的散列表"><a href="#5-字典中的散列表" class="headerlink" title="5 字典中的散列表"></a>5 字典中的散列表</h3><p>散列表其实是一个稀疏数组（总是有空白元素的数组称为稀疏数组）。 在一般的数据结构教材中，散列表里的单元通常叫作表元（bucket）。 在 dict 的散列表当中，每个键值对都占用一个表元，每个表元都有两 个部分，一个是对键的引用，另一个是对值的引用。因为所有表元的大小一致（因为值的引用大小是固定的，不管值本身有多大），所以可以通过偏移量来读取某个表元。 </p>
<h4 id="散列表（哈希表）扩展"><a href="#散列表（哈希表）扩展" class="headerlink" title="散列表（哈希表）扩展"></a>散列表（哈希表）扩展</h4><p>语言底层的数据结构都是大同小异的</p>
<p>散列表就是通过特定的hash函数把key的值计算成hash值，然后找到指定的位置插入，所以散列表是有初始大小，且一开始内部元素都是空，当到达阈值（或者加载因子）（java中hashmap的加载因子为0.75）就会创建一个更大的散列表把原来散列表的数据复制过去</p>
<p>加载因子越大，填满的元素越多，空间利用率越高，但发生冲突的机会变大了；</p>
<p>加载因子越小，填满的元素越少，冲突发生的机会减小，但空间浪费了更多了，而且还会提高扩容rehash操作的次数。</p>
<p>冲突的机会越大，说明需要查找的数据还需要通过另一个途径查找，这样查找的成本就越高。因此，必须在“冲突的机会”与“空间利用率”之间，寻找一种平衡与折衷。</p>
<h4 id="如何处理hash冲突"><a href="#如何处理hash冲突" class="headerlink" title="如何处理hash冲突"></a>如何处理hash冲突</h4><ul>
<li>开放地址法<ul>
<li>线性探查</li>
<li>平方探查</li>
<li>伪随机</li>
</ul>
</li>
<li>再哈希</li>
<li>公共地址</li>
<li>链地址法</li>
</ul>
<p>python中解决hash冲突的办法：开放寻址</p>
<p><img src="https://tva1.sinaimg.cn/large/008i3skNly1gtcrmf3n0hj615s0nkac902.jpg" alt="image-20210811130442166" loading="lazy"></p>
<h4 id="dict的底层实现"><a href="#dict的底层实现" class="headerlink" title="dict的底层实现"></a>dict的底层实现</h4><p>3.6之前使用的是一个二维数组，在遍历的时候实际上就是遍历这个二维数组</p>
<pre class=" language-python"><code class="language-python">my_dict<span class="token punctuation">[</span><span class="token string">'age'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">26</span>
my_dict<span class="token punctuation">[</span><span class="token string">'salary'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">999999</span>

<span class="token triple-quoted-string string">'''
此时的内存示意图
[[-4234469173262486640, 指向salary的指针, 指向999999的指针],
[1545085610920597121, 执行age的指针, 指向26的指针],
[---, ---, ---],
[---, ---, ---],
[---, ---, ---],
[1278649844881305901, 指向name的指针, 指向kingname的指针],
[---, ---, ---],
[---, ---, ---]]
'''</span></code></pre>
<p>3.6之后</p>
<p>循环的时候循环的是entries，entries中的数据时按插入顺序存的，通过hash得到的值的位置在indices指定</p>
<pre class=" language-python"><code class="language-python">my_dict<span class="token punctuation">[</span><span class="token string">'name'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">'kingname'</span>

<span class="token triple-quoted-string string">'''
此时的内存示意图
indices = [None, 0, None, None, None, None, None, None]

entries = [[-5954193068542476671, 指向name的指针, 执行kingname的指针]]
'''</span>
</code></pre>
<p>老的方式，当二维数组有8行的时候，即使有效数据只有3行，但它占用的内存空间还是 8 <em>24 = 192 byte。但使用新的方式，如果只有三行有效数据，那么<code>entries</code>也就只有3行，占用的空间为3</em> 24 =72 byte，而<code>indices</code>由于只是一个一维的数组，只占用8 byte，所以一共占用 80 byte。内存占用只有原来的41%。</p>
<h2 id="第四章-字节与序列"><a href="#第四章-字节与序列" class="headerlink" title="第四章 字节与序列"></a>第四章 字节与序列</h2><p>todo</p>
<h2 id="第五章-一等函数"><a href="#第五章-一等函数" class="headerlink" title="第五章 一等函数"></a>第五章 一等函数</h2><p>tips：面试考点 </p>
<p>type是所有类的元类，object是所有类的父类，同时type是object的类，object是type的父类</p>
</div><div id="reward-container"><span class="hty-icon-button button-glow" id="reward-button" title="打赏" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === &quot;none&quot;) ? &quot;block&quot; : &quot;none&quot;;"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-hand-coin-line"></use></svg></span><div id="reward-comment">点我就给你看点有意思的</div><div id="qr" style="display:none;"><div style="display:inline-block"><a target="_blank" rel="noopener" href="https://gitee.com/huang_zhao/hz/raw/master/hz/alipay.png"><img loading="lazy" src="https://gitee.com/huang_zhao/hz/raw/master/hz/alipay.png" alt="支付宝" title="支付宝"></a><div><span style="color:#00A3EE"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-alipay-line"></use></svg></span></div></div><div style="display:inline-block"><a target="_blank" rel="noopener" href="https://gitee.com/huang_zhao/hz/raw/master/hz/qqpay.jpg"><img loading="lazy" src="https://gitee.com/huang_zhao/hz/raw/master/hz/qqpay.jpg" alt="QQ 支付" title="QQ 支付"></a><div><span style="color:#12B7F5"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-qq-line"></use></svg></span></div></div><div style="display:inline-block"><a target="_blank" rel="noopener" href="https://gitee.com/huang_zhao/hz/raw/master/hz/wxpay.jpg"><img loading="lazy" src="https://gitee.com/huang_zhao/hz/raw/master/hz/wxpay.jpg" alt="微信支付" title="微信支付"></a><div><span style="color:#2DC100"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-wechat-pay-line"></use></svg></span></div></div></div></div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong>爱肖彤真是太好了</li><li class="post-copyright-link"><strong>本文链接：</strong><a href="http://huang_zhao.gitee.io/task/2021/06/27/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/%E6%B5%81%E7%95%85%E7%9A%84python%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/" title="流畅的python学习记录">http://huang_zhao.gitee.io/task/2021/06/27/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/%E6%B5%81%E7%95%85%E7%9A%84python%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/</a></li><li class="post-copyright-license"><strong>版权声明：</strong>本博客所有文章除特别声明外，均默认采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="noopener" title="CC BY-NC-SA 4.0 "><svg class="icon"><use xlink:href="#icon-creative-commons-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-by-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-nc-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-sa-line"></use></svg></a> 许可协议。</li></ul></section></article><div class="post-nav"><div class="post-nav-item"><a class="post-nav-prev" href="/task/2021/07/01/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/Mysql%E6%B7%B1%E5%85%A5%E5%AD%A6%E4%B9%A0/" rel="prev" title="mysql深入学习"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-left-s-line"></use></svg><span class="post-nav-text">mysql深入学习</span></a></div><div class="post-nav-item"><a class="post-nav-next" href="/task/2021/06/27/%E6%95%B0%E6%8D%AE%E5%BA%93/redis/Redis/" rel="next" title="Redis"><span class="post-nav-text">Redis</span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-right-s-line"></use></svg></a></div></div></div></main><footer class="sidebar-translate" id="footer"><div class="copyright"><span>&copy; 2019 – 2022 </span><span class="with-love" id="animate"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-cloud-line"></use></svg></span><span class="author"> 爱肖彤真是太好了</span></div><div class="powered"><span>由 <a href="https://hexo.io" target="_blank" rel="noopener">Hexo</a> 驱动 v5.1.1</span><span class="footer-separator">|</span><span>主题 - <a rel="noopener" href="https://github.com/YunYouJun/hexo-theme-yun" target="_blank"><span>Yun</span></a> v0.9.7</span></div><div class="live_time"><span>本博客已萌萌哒地运行</span><span id="display_live_time"></span><span class="moe-text">(●'◡'●)</span><script>function blog_live_time() {
  window.setTimeout(blog_live_time, 1000);
  const start = new Date('2019-04-12T00:00:00');
  const now = new Date();
  const timeDiff = (now.getTime() - start.getTime());
  const msPerMinute = 60 * 1000;
  const msPerHour = 60 * msPerMinute;
  const msPerDay = 24 * msPerHour;
  const passDay = Math.floor(timeDiff / msPerDay);
  const passHour = Math.floor((timeDiff % msPerDay) / 60 / 60 / 1000);
  const passMinute = Math.floor((timeDiff % msPerHour) / 60 / 1000);
  const passSecond = Math.floor((timeDiff % msPerMinute) / 1000);
  display_live_time.innerHTML = " " + passDay + " 天 " + passHour + " 小时 " + passMinute + " 分 " + passSecond + " 秒";
}
blog_live_time();
</script></div><div id="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_site_uv" title="总访客量"><span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-user-line"></use></svg></span><span id="busuanzi_value_site_uv"></span></span><span class="footer-separator">|</span><span id="busuanzi_container_site_pv" title="总访问量"><span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-eye-line"></use></svg></span><span id="busuanzi_value_site_pv"></span></span></div></footer><a class="hty-icon-button" id="goUp" aria-label="back-to-top" href="#"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-up-s-line"></use></svg><svg class="progress-circle-container" viewBox="0 0 100 100"><circle class="progress-circle" id="progressCircle" cx="50" cy="50" r="48" fill="none" stroke="#0078E7" stroke-width="2" stroke-linecap="round"></circle></svg></a><a class="popup-trigger hty-icon-button icon-search" id="search" href="javascript:;" title="搜索"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-search-line"></use></svg></span></a><script>window.addEventListener("DOMContentLoaded", () => {
  // Handle and trigger popup window
  document.querySelector(".popup-trigger").addEventListener("click", () => {
    document.querySelector(".popup").classList.add("show");
    setTimeout(() => {
      document.querySelector(".search-input").focus();
    }, 100);
  });

  // Monitor main search box
  const onPopupClose = () => {
    document.querySelector(".popup").classList.remove("show");
  };

  document.querySelector(".popup-btn-close").addEventListener("click", () => {
    onPopupClose();
  });

  window.addEventListener("keyup", event => {
    if (event.key === "Escape") {
      onPopupClose();
    }
  });
});
</script><script src="/task/js/search/local-search.js" defer></script><div class="popup search-popup"><div class="search-header"><span class="popup-btn-close close-icon hty-icon-button"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-close-line"></use></svg></span></div><div class="search-input-container"><input class="search-input" id="local-search-input" type="text" placeholder="搜索..." value=""></div><div id="local-search-result"></div></div></div><script defer src="/task/js/utils.js"></script><script defer src="/task/js/hexo-theme-yun.js"></script></body></html>